import sys, os

from liwe.module import LiweModule
from os3.utils.image_handler import ImageHandler

class Showcase ( LiweModule ):

	SHOWCASE_CONF_FIELDS = [ 'id', 'name', 'playtime', 'w', 'h', 'created' ]

        def __init__ ( self, liwe ):
                super ( Showcase, self ).__init__ ( liwe, "showcase" )

                self.dbm = self.liwe.dbm
		self._dest_dir = 'site/showcase/images'
		self._img_width = self.cfg.get ( "image.w", 400 )
		self._img_height = self.cfg.get ( "image.h", 300 )


	#{{{ Gestione Showcase_conf
	# ..function:: Shocase.add_conf ( self, id, name, interval, w , h )
	#	Add or Update row in showcase_conf table
	#	Return id added or modified
	#	:param	id:		the uniquie id 
	#	:param	name:		the name of shocase config
	#	:param	playtime:	the interval of crossfading
	#	:param	w:		resizing width of the uploaded images
	#	:param	h:		resizing height of the uploaded images
	def add_conf ( self, id = 0, name = '', playtime = 0, w = 0 , h = 0 ):
	
                vals = { 'id' :  id,
                        'name'  : name,
                        'playtime' : playtime,
                        'w' : w,
                        'h' : h,
                        'created' : '*NOW()'
                        }

                if not id:
                        if "id" in vals: del vals [ 'id' ]
                        self.dbm.insert ( 'showcase_conf' , vals )
                        last_id = self.dbm.insert_id ( )
                        return last_id
		
		vals.pop ( 'h' )
		vals.pop ( 'w' )	
                self.dbm.update ( 'showcase_conf', vals, "id = %s" % id )
                return id

	# ..function:: Showcase.get_conf ( self, id, name )
	#	return corrensponding row filtred by id or name for table showcase_config
	#	:param id:	id of config
	#	:param name:	name of config
	def get_conf ( self, id = 0, name = '' ):
		res = []
		if( not id ) and  ( not name ) :  return res
		conds = []
		if id : conds.append ( 'id = %s ' % id )
		if name : conds.append ( "name = '%s' " % name )
		
		res = self.dbm.single_row ( 'showcase_conf', self.SHOWCASE_CONF_FIELDS , ' AND '.join ( conds ) )
		return res

	# ..function:: Showcase.list_conf ( self )
	#	return dictionary that contain rows and totrows in shocase_conf
	#	:param start_point:	start point for LIMIT condition
	#	:param do_count:	number of row for limit condition
	def list_conf ( self, quant=10, start_point = 0,  do_count = 0, ):

		
		tot_rows=0
		if do_count:
			tot_rows = self.dbm.count ( 'showcase_conf', self.SHOWCASE_CONF_FIELDS )
		
		rows = self.dbm.all_rows ( 'showcase_conf',  self.SHOWCASE_CONF_FIELDS, extras = 'LIMIT %s, %s' % ( start_point, quant ) )
		if not rows: rows = []
		return { "rows" : rows, "tot_rows" : tot_rows }

	# ..function:: Showcase.del_conf ( self , ids )
	#	delete configuration all row for table showcase child
	#	:param ids:	string width single id or multiple separeted |
	def del_conf ( self, ids = '' ):

		if not ids: return
		id_lst = ids.split ( '|' )
		for id in id_lst:
			
			lst = self.dbm.all_rows ( "showcase", [ 'id' ] , "id_conf = %s" % id )
			if lst:
				ids_sc = '|'.join ( [ str( x['id'] ) for x in lst ])			
				self.delete ( ids_sc )
			self.dbm.delete ( "showcase_conf", "id = %s " % id )
		return
		
	#}}}



	#..function:: Showcase.add ( self, id, id_conf, posm descr , file_obj, lnk)
	#	add o update single row in showcase table, save image with  H and W for the assigned configuration
	#	:param id:	ID number for this image
	#	:param id_conf	ID configuration number
	#	:param pos 	number position
	#	:param descr	string description of the image abitually usede in alt or title
	#	:param lnk	string url  used in click event
	def add ( self, id = 0, id_conf = 0, pos = 0, descr = '', file_obj = None, lnk = '' ):
		
		dct = {
			'id_conf'	: id_conf,
			'pos'		: pos,
			'descr'		: descr,
			'created'	: '*NOW()',
			'lnk'		: lnk
			}

		if file_obj:
			file_split = os.path.splitext ( file_obj [ 'filename' ] )
			dct [ 'file_name' ] = file_split [ 0 ]
			dct [ 'ext' ]	    = file_split [ 1 ]
			dct [ 'kind' ]	    = file_obj [ 'type' ]
		#INSERT
		if not id:	
			dct [ 'id' ] =  ''
			self.dbm.insert ( "showcase", dct )
			id = self.dbm.insert_id ()
		else:		
		#UPDATE
			fields = [ 'id', 'id_conf', 'kind', 'pos', 'descr', 'file_name', 'ext', 'created', 'lnk' ]
			chk = self.dbm.single_row ( "showcase", fields,  "id = %s" % id )
			if chk and file_obj:
				#remove file if it does exits
				self._remove_file ( id = chk [ 'id' ] )

			self.dbm.update ( "showcase", dct, "id = %s" % id )

		#salva file
		self._save_file ( id, id_conf, file_obj ) 
		

		"""
		no longer supported
		#salva tag
		if tags :
	                self.liwe.invoke ( "tags.admin.del_all_tags", id_obj = id, id_site = self.site_id, module = "showcase" ) 
        	        self.liwe.invoke ( "tags.ajax.tag_object", id_obj = id, id_site = self.site_id, tags = tags, module = "showcase" ) 
		"""


	#..function:: Showcase._save_file ( id, file_obj )
	#	save file whith H W specified in id_conf
	#	:param id	ID's showcase
	#	:param id_conf	ID's showcase_conf
	#	:param file_obj	file to save
	def _save_file ( self, id = '', id_conf = 0, file_obj = None ):
		if not id or not file_obj or not id_conf: return

		name = file_obj [ 'filename' ]
		fil = file_obj [ 'file' ]
		fil.seek ( 0, os.SEEK_END )
		size = fil.tell ()
		fil.seek ( 0 )

		split = os.path.splitext ( file_obj [ 'filename' ] )
		if split:
			ext = split [ 1 ] 
		else:
			ext = ""

		ext = ext.lower ()

		fout_name = os.path.join ( self._dest_dir , "temp_%s%s" % ( id, ext ) )
		fout = open ( fout_name, "wb" )
		fout.write ( fil.read () )
		fout.close ()

		#get conf
		conf = self.get_conf ( id = id_conf )

		self._create_thumb_image ( self._dest_dir, id, conf, fout_name )
		self._remove_file ( name =  "temp_%s%s" % ( id, ext ) )
	
	#..function:: Showcase._create_thumb_image ( path_name, id, conf, full_dest_name )
	#	Scale and save image in site/showcase/images
	#	:param path_name	path to stock image scaled
	#	:param id		ID'showcase
	#	:param conf		Configiration row from showcase_config table
	#	:param full_dest_name	Original file path
        def _create_thumb_image ( self, path_name, id, conf, full_dest_name ):
                ih = ImageHandler ()
                im = ih.load ( full_dest_name )
                im.toRGB ()

		_width = conf [ 'w']
		if _width == 0 : _width = self._img_width 

		_height = conf [ 'h' ] 
		if _height == 0 : _height = self._img_height 
	
                im.scale ( _width, _height )
                im.save ( os.path.join ( path_name, "%s.jpg" % id ), "JPEG" )


	#..function:: Showcase._def_mime_type ( path_name )
	#	Return file's mime
	#	:param path_name	path of file to get mime 
        def _define_mime_type ( self, path_name = '' ):
                mimetypes.init ()
                mime = mimetypes.guess_type ( path_name )
                return mime

	#..function:: Showcase._remove_file
	#	Remove file from file system /site/showcase/images
	#	:param id	ID's showcase
	#	:param ext	file extension
	#	:param name	file name
	def _remove_file ( self, id = '',  ext = '.jpg', name = '' ):
		
		if not name:
			name =  "%s%s" % ( id, ext )
		path_name =  os.path.join ( self._dest_dir , "%s" % name )
		try:
			os.remove ( path_name )
		except:
			return 2
	#..function:: Showcase.delete ( ids )
	#	Remove row/s from showcase table, remove imgage
	#	:param ids	ID's or IDs 
	def delete ( self, ids = '' ):
		
		if not ids: return

		id_lst = ids.split ( '|' )
		for id in id_lst:
			fields = [ 'ext' ]
			item = self.dbm.single_row ( "showcase", fields,  "id = %s" % id )
			#remove imgages
			self._remove_file ( id = id )
			"""
			no longer supported
			#remove tags
	                self.liwe.invoke ( "tags.admin.del_all_tags", id_obj = id, id_site = self.site_id, module = "showcase" ) 
			"""
			self.dbm.delete ( "showcase", "id = %s " % id )

	#..function:: Showcase.list ( id_conf, kind, ext, start_point, do_count )
	#	Return list for showcase table filtred by params
	#	:param id_conf		ID's showcase_conf
	#	:param conf_name	showcase_conf name
	#	:param kind		Kind of file
	#	:param ext		extension's file
	#	:param start_point	pagination start_point
	#	:param do_count		count tot rows
	def list ( self, id_conf = 0, conf_name = '', kind = '', ext = '', tag = '' , start_point = 0, do_count = 0 ):
		
		if not id_conf and not conf_name:  return { "rows" : [] }
		
		if not id_conf:
			conf = self.get_conf ( name = conf_name )
			id_conf = conf [ 'id' ]

		conds = []
		fields = [ 'id', 'id_conf',  'kind', 'pos', 'descr', 'file_name', 'ext', 'created', 'lnk' ]
		if id_conf: conds.append ( "id_conf = %s" % id_conf )
		if kind: conds.append ( "kind = '%s'" % kind )
		if ext: conds.append ( "ext = '%s'" % ext )

		tot_rows = 0
		if do_count:
			tot_rows = self.dbm.count ( "showcase", fields, ",".join ( conds ), extras = 'ORDER BY pos' )
		res = self.dbm.all_rows ( "showcase", fields, ",".join ( conds ), extras = 'ORDER BY pos' )
		if not res: 
			res = []
			return { "rows" : res, "tot_rows" : tot_rows }
		return { "rows" : res, "tot_rows" : tot_rows }

	#..function:: Showcase.get ( id )
	#	Return corrensponding row of showcase table
	#	:param id	ID's showcase table
	def get ( self, id = id ):
		
		fields = [ 'id', 'id_conf',  'kind', 'pos', 'descr', 'file_name', 'ext', 'created', 'lnk' ]
		conds = 'id = %s' % id
		res = self.dbm.single_row ( [ "showcase" ], fields, conds )
		if not res : return
		return res
